import { View, Text, Image } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useState, useEffect, useLayoutEffect } from 'react'
import Header from '@/myComponent/header'
import Card from '@/myComponent/card'
import { LgTab, LgTabs } from '@/pages/components/tabs'
import LgSearch from '@/pages/components/searchInput'
import { useDocumentTitle, useGetIsMapArray, useGetTabBg, useMockAddr } from '@/utils/myUtils'
import _ from 'lodash'
import { HttpGet, HttpPut } from '@/network/servers'
import { connect } from 'react-redux'
import LgRefreshPage from '../components/refreshPage'
import LgEmptyContent from '../components/emptyContent'
import SearchPageComp from '../searchPageComp'
import './index.scss'

function App(props) {

    const {
        userInfo,
        sysInfo,
    } = props

    useDocumentTitle('部门公告')

    const [dropDownList, setDropDownList] = useState<any>([
        { typeId: '0', typeName: '全部' },
    ])

    const [currentTab, setCurrentTab] = useState<any>({ typeId: '', typeName: '全部' })
    const [keyword, setKeyword] = useState('')
    const [dataList, setDataList] = useState<any>([])
    const [dataList2, setDataList2] = useState<any>([])

    const [totalPage, setTotalPage] = useState(0)
    const [pullCount, setPullCount] = useState(1)

    const [total, setTotal] = useState(0)
    const [showSearch, setShowSearch] = useState(false)
    const [h, setH] = useState('')


    // 搜索变化
    const searchHandle = _.debounce((value) => {
        setKeyword(value.trim())
    }, 500, { trailing: true })

    const choTab = (value, key) => {
        let currentType = { typeId: '', typeName: '全部' }
        useGetIsMapArray(dropDownList) && dropDownList.forEach(item => {
            if (item.typeName === key) {
                currentType = item
            }
        })
        setPullCount(1)
        setCurrentTab(currentType)
    }

    const goDetail = (item) => {
        Taro.navigateTo({
            url: `pages/detail/index?bulletinId=${item.bulletinId}`
        })
    }

    // 无限加载
    const onPull = () => {
        if (totalPage > pullCount) {
            setPullCount(pullCount + 1)
            getList(pullCount + 1)
        } else {
            Taro.showToast({
                title: '到底啦',
                icon: 'none'
            })
        }
    }
    // 下拉刷新
    const onDown = () => {
        setPullCount(1)
        getList()
        setTimeout(() => {
            Taro.showToast({
                title: '刷新成功'
            })
        }, 500)
    }

    // 获取类型tab列表
    const getCommonData = () => {
        HttpGet({
            url: '/api/bulletin/type/statistics/released/num',
            data: {
                eduId: userInfo.eduId,
                userType: userInfo.userType,
                identityCode: userInfo.identityCode,
            }
        }).then((typeList) => {
            typeList.unshift({ typeId: '', typeName: '全部' })

            setDropDownList(typeList)
        })
    }

    // 获取公告列表
    const getList = (n = pullCount) => {
        HttpGet({
            url: `/api/bulletin/board/list/page/1/${n * 10}`,
            data: {
                eduId: userInfo.eduId,
                keyword,
                typeId: currentTab.typeId,
                userId: userInfo.userId,
                userType: userInfo.userType,
                status: 1,
                identityCode: userInfo.identityCode
            },
            load: true,
            isBackAll: true,
        }).then((result) => {

            let bulletinList = result.data

            bulletinList = bulletinList.sort((a, b) => {
                if (a.status === '1' && a.seat === '1') {
                    return -1;
                }
                if (b.status === '1' && b.seat === '1') {
                    return 1;
                }
                if (a.status === '0') {
                    return -1;
                }
                if (b.status === '0') {
                    return 1;
                }
                if (a.readStatus === '0') {
                    return -1;
                }
                if (b.readStatus === '0') { //已读的排序靠后(修改)
                    return 1;
                }
                if (a.status === '1' && a.seat === '0') {
                    return -1;
                }
                if (b.status === '1' && b.seat === '0') {
                    return 1;
                }
                return 0;
            });

            setTotalPage(Math.ceil(Number(result.total) / 10))
            setTotal(result.total)
            setDataList(bulletinList)
        })
    }
    // 获取搜索列表
    const getList2 = (n = pullCount, h) => {
        if (!h) {
            return
        }
        setH(h)
        HttpGet({
            url: `/api/bulletin/board/list/page/1/${n * 10}`,
            data: {
                eduId: userInfo.eduId,
                keyword: h,
                typeId: currentTab.typeId,
                userId: userInfo.userId,
                userType: userInfo.userType,
                status: 1,
                identityCode: userInfo.identityCode
            },
            load: true,
            isBackAll: true,
        }).then((result) => {
            let bulletinList = result.data

            bulletinList = bulletinList.sort((a, b) => {
                if (a.status === '1' && a.seat === '1') {
                    return -1;
                }
                if (b.status === '1' && b.seat === '1') {
                    return 1;
                }
                if (a.status === '0') {
                    return -1;
                }
                if (b.status === '0') {
                    return 1;
                }
                if (a.readStatus === '0') {
                    return -1;
                }
                if (b.readStatus === '0') { //已读的排序靠后(修改)
                    return 1;
                }
                if (a.status === '1' && a.seat === '0') {
                    return -1;
                }
                if (b.status === '1' && b.seat === '0') {
                    return 1;
                }
                return 0;
            });
            setDataList2(bulletinList)
        })
    }

    // 打开搜索框
    const openSearch = (e) => {
        e.stopPropagation();
        setShowSearch(true);
    }

    useEffect(() => {
        getCommonData()
    }, [])

    useEffect(() => {
        getList()
    }, [keyword, currentTab])

    useLayoutEffect(() => {
        window.refreshPage = getList
    }, [currentTab, pullCount, keyword])

    const childenDom = () => {
        console.log(dataList2)
        console.log(h)
        return (
            <View>
                {
                    dataList2.length > 0 ? dataList2.map(i => {
                        console.log(i.title.indexOf(h))
                        let indexH = i.title.indexOf(h)
                        return (
                            <View onClick={() => { goDetail(i) }} className='itemList'>{i.title.slice(0, indexH)} <span style={{ color: '#ff7d27' }}>{i.title.slice(indexH, indexH + h.length)}</span> {i.title.slice(indexH + h.length)}</View>
                        )
                    }) : ''
                }
            </View>
        )
    }

    return (
        <View className='announcement_user'>
            <Header
                title='部门公告'
            />
            <View className='tab_area' style={useGetTabBg()}>
                <LgTabs
                    onClick={choTab}
                    showIcon
                    customIcon={<></>}
                    default={0}
                >
                    {
                        useGetIsMapArray(dropDownList) && dropDownList.map((item, index) => {
                            return (
                                <LgTab
                                    key={index}
                                    count={0}
                                    title={item.typeName}
                                />
                            )
                        })
                    }
                </LgTabs>
            </View>
            <View className="search_option">
                <View className='announce_count'>
                    共
                    <Text style={{ color: '#333333' }}>{total}</Text>
                    个公告
                </View>
                <View className='my_ipt'>
                    {
                        // showSearch ?
                        //     <LgSearch
                        //         value={keyword}
                        //         onConfirm={(value: string) => setKeyword(value.trim())}
                        //         placeholder='搜索公告标题/部门'
                        //         onInput={searchHandle}
                        //     />
                        //     :
                        <View className='my_search_icon' onClick={(e) => openSearch(e)}></View>
                    }
                </View>
            </View>
            <SearchPageComp
                setDataList={() => {
                    setDataList2([])
                }}
                placeholder={'搜索部门通知标题'}
                visible={showSearch}
                dataList={dataList2}
                loading={false}
                childrenDom={childenDom()}
                setVisible={() => {
                    setShowSearch(false)
                }}
                setWords={(h) => { getList2(1, h) }}
            >
            </SearchPageComp>
            <View className='list_container' onClick={() => setShowSearch(false)}>
                <LgRefreshPage
                    className='index'
                    onPull={onPull}
                    onDown={onDown}
                    downText={['下拉刷新', '释放刷新']}
                    pullText={['上拉加载更多', '释放加载更多']}>
                    {
                        useGetIsMapArray(dataList) ? dataList.map((item) =>
                            <Card
                                key={item.bulletinId}
                                onClick={() => goDetail(item)}
                                state={item.readStatus == 0 ? 'active' : 'unActive'}
                                data={item}
                            />
                        ) :
                            <View className='empty_container'>
                                <LgEmptyContent type='B' text={keyword ? `暂未搜索到${keyword}相关内容` : '暂无内容'} />
                            </View>
                    }
                </LgRefreshPage>
            </View>
        </View>
    )
}

const mainProps = ({ commonData }) => {
    return {
        userInfo: commonData.userInfo,
        sysInfo: commonData.sysInfo,
    }
}

export default connect(mainProps)(App)